/**
 * Workers API Routes
 * 
 * Handles worker pool management and parallel execution
 */

import { Hono } from 'hono';
import type { ApiResponse } from '@/types';
import { logger } from '@/utils/logger';
import { workerManager } from '@/workers';

export const workersRoutes = new Hono();

/**
 * GET /api/workers/statistics
 * 
 * Get worker pool statistics
 */
workersRoutes.get('/statistics', (c) => {
  const stats = workerManager.getStatistics();

  const response: ApiResponse = {
    success: true,
    data: stats,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * POST /api/workers/initialize
 * 
 * Initialize worker pools
 */
workersRoutes.post('/initialize', async (c) => {
  try {
    await workerManager.initialize();

    logger.info('Worker pools initialized via API');

    const response: ApiResponse = {
      success: true,
      data: { initialized: true },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to initialize worker pools', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'WORKER_INIT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * POST /api/workers/shutdown
 * 
 * Shutdown worker pools
 */
workersRoutes.post('/shutdown', async (c) => {
  try {
    await workerManager.shutdown();

    logger.info('Worker pools shut down via API');

    const response: ApiResponse = {
      success: true,
      data: { shutdown: true },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to shutdown worker pools', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'WORKER_SHUTDOWN_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * POST /api/workers/execute
 * 
 * Execute a single agent query in a worker
 */
workersRoutes.post('/execute', async (c) => {
  try {
    const body = await c.req.json();
    const { prompt, options } = body;

    if (!prompt) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_REQUEST',
          message: 'Missing required field: prompt',
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    const result = await workerManager.executeAgentQuery(prompt, options);

    const response: ApiResponse = {
      success: true,
      data: { result },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to execute query in worker', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'WORKER_EXECUTION_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * POST /api/workers/execute-parallel
 * 
 * Execute multiple agent queries in parallel
 */
workersRoutes.post('/execute-parallel', async (c) => {
  try {
    const body = await c.req.json();
    const { queries } = body;

    if (!Array.isArray(queries) || queries.length === 0) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_REQUEST',
          message: 'Missing or invalid field: queries (must be a non-empty array)',
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    const startTime = Date.now();
    const results = await workerManager.executeAgentQueriesParallel(queries);
    const duration = Date.now() - startTime;

    const response: ApiResponse = {
      success: true,
      data: {
        results,
        count: results.length,
        duration,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to execute parallel queries', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'PARALLEL_EXECUTION_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

